package online_store.servlet;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.FrameworkServlet;

import online_store.model.bus.UserBus;
import online_store.model.dto.UserDTO;
import online_store.utils.Constants;

public class LoginServlet extends HttpServlet{
	
	
	@Override
	public void init(ServletConfig config) throws ServletException {
//		userBus = new UserBus();
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		System.out.println("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");
		
		String servletName = FrameworkServlet.class.getName() + ".CONTEXT.spring-mvc";
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext(), servletName);
		UserBus userBus = (UserBus)context.getBean("userBus");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String loginkeeping = request.getParameter("loginkeeping");
		
		String errorMessage = "";
		
		UserDTO user = userBus.findByUser_Pass(username, password);
		if(user == null){
			errorMessage = "?loginErrorMessage=invalid-username-password";
		}
		
		if(errorMessage.isEmpty()){ //login successful
			HttpSession session = request.getSession();
			session.setAttribute("user_id", user.getId());
			session.setAttribute("username", user.getUsername());
			
			//store data on cookie
			if(loginkeeping != null && loginkeeping.equals("true")){
				Cookie userIdCookie = new Cookie(Constants.ONLINE_STORE_USERID, user.getId() + "");
				Cookie usernameCookie = new Cookie(Constants.ONLINE_STORE_USERNAME, user.getUsername());
				
				userIdCookie.setMaxAge(1000 * 60 * 60);
				usernameCookie.setMaxAge(1000 * 60 * 60); //1 hour
				
				userIdCookie.setPath(request.getContextPath() + "/");
				usernameCookie.setPath(request.getContextPath() + "/");
				
				response.addCookie(usernameCookie);
				response.addCookie(userIdCookie);
			}
			
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		}else{
			response.sendRedirect(request.getContextPath() + "/user/login.jsp" + errorMessage + "#tologin");
		}
	}
}
